package com.sunducation.co.mcvw;

import lombok.Data;

import java.util.Arrays;
import java.util.Date;

/**
 * @description: 解决----内部存在可变对象引起的BUG
 * @author:chenwenbiao
 * @createTime:2019/7/9 14:33
 * @Version：1.0
 **/
@Data
public class MutableObjectTest2 {

    private Integer id;
    private Integer[] ids;
    private Date gmtCreate;

    public void setIds(Integer[] ids) {
        if(ids != null){
            this.ids = ids.clone();
        }
        else {
            this.ids = null;
        }
    }

    public void setGmtCreate(Date gmtCreate) {
        if(gmtCreate != null){
            this.gmtCreate = (Date) gmtCreate.clone();
        }
        else {
            this.gmtCreate = null;
        }
    }

    public static void main(String[] argv){
        MutableObjectTest2 mutableObjectTest = new MutableObjectTest2();

        /**
         * Integer测试，结果不变,Integer没有提供set的方法
         */
        Integer id = new Integer(12345);
        mutableObjectTest.setId(id);
        System.out.println(mutableObjectTest.getId());
        id = 123;
        System.out.println(mutableObjectTest.getId());



        /**
         * Date测试，结果被篡改
         */
        Date date = new Date();
        mutableObjectTest.setGmtCreate(date);
        System.out.println(mutableObjectTest.getGmtCreate());
        date.setYear(12);
        System.out.println(mutableObjectTest.getGmtCreate());


        /**
         * Integer[]测试，结果被篡改
         */
        Integer[] ids = {1,2,3};
        mutableObjectTest.setIds(ids);

        System.out.println(Arrays.asList(mutableObjectTest.getIds()));
        ids[1] = 0;
        System.out.println(Arrays.asList(mutableObjectTest.getIds()));

    }
}
